package com.linghang.wusthelper.service.Impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.linghang.wusthelper.common.ServerResponse;
import com.linghang.wusthelper.dao.primary.LhstudioDao;
import com.linghang.wusthelper.dao.primary.StudentDao;
import com.linghang.wusthelper.redis.RedisService;
import com.linghang.wusthelper.service.LhstudioService;
import com.linghang.wusthelper.spider.jwc.JwcSimLogin;
import com.linghang.wusthelper.util.EncryptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Service("LhstudioService")
public class LhstudioServiceImpl implements LhstudioService {

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private LhstudioDao lhstudioDao;

    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     * @param stuNum
     * @param password
     * @return
     */
    @Override
    public ServerResponse login(String stuNum, String password) {
        int result = lhstudioDao.checkExist(stuNum);
        if (result == 0){
            return ServerResponse.createByErrorMsg("没有权限");
        }
        int result2 = studentDao.lhlogin(stuNum, EncryptUtil.encryptPasswd(password));
        if (result2 == 0){
            return ServerResponse.createByErrorMsg("账号不存在或者密码错误");
        }
        Map<String,String> resultMap = JwcSimLogin.login(stuNum,password);
        if (resultMap.get("code").equals("0")) {
            log.error("教务处无法访问");
            //  教务处无法访问
            return ServerResponse.createByJWCError();
        } else if (resultMap.get("code").equals("2")) {
            //  密码错误或账号不存在
            return ServerResponse.createByErrorMsg(resultMap.get("errorMsg"));
        } else{
            String secret = String.valueOf(UUID.randomUUID());
            Algorithm algorithm = Algorithm.HMAC256(secret);
            Long nowMillis = System.currentTimeMillis();
            Date now = new Date(nowMillis);
            Date exp = new Date(nowMillis+1800);
            String token = JWT.create()
                    .withIssuer("lhstudio")
                    .withAudience("wusthelper")
                    .withClaim("stuNum",stuNum)
                    .withIssuedAt(now)
                    .withExpiresAt(exp)
                    .sign(algorithm);
            redisService.set(stuNum+":lhUUID",secret,1800);
            return ServerResponse.createBySuccess("登录成功",token);
        }
    }
}
